/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserLabel;
import com.yami.shop.bean.model.VipPackage;
import com.yami.shop.bean.param.VipBuyParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.dao.VipPackageMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.UserLabelService;
import com.yami.shop.service.UserService;
import com.yami.shop.service.VipPackageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lgh on 2018/10/26.
 */
@RestController
@RequestMapping("/p/vip")
@Api(tags = "vip接口")
public class VipController {
    @Autowired
    private VipPackageService vipPackageService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VipPackageMapper vipPackageMapper;

    @Autowired
    private UserService userService;

    @GetMapping("/normal")
    @ApiOperation(value = "获取Vip套餐", notes = "返回普通vip套餐")
    public ResponseEntity<List<VipPackage>> normal() {
        List<VipPackage> list = vipPackageService.list(new LambdaQueryWrapper<>(new VipPackage())
                                                         .eq(VipPackage::getStatus,1)
                                                            .eq(VipPackage::getMark,1));
        return ResponseEntity.ok(list);
    }

    @GetMapping("/cheap")
    @ApiOperation(value = "获取新人特惠套餐", notes = "当前用户有特惠套餐时，返回套餐列表；没有特惠套餐时，返回空列表")
    public ResponseEntity<List<VipPackage>> cheap() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);

        List<VipPackage> list = vipPackageService.list(new LambdaQueryWrapper<>(new VipPackage())
                .eq(VipPackage::getStatus,1).eq(VipPackage::getMark,0));

        if(user.getDiscount()>0){
            return ResponseEntity.ok(list);
        }else{
            return ResponseEntity.ok(new ArrayList<>());
        }
    }

    //测试支付用接口，无法在线上环境中使用 线上见JiaoyouOrderServiceImpl
    @Deprecated
    @PostMapping
    @ApiOperation(value = "购买VIP", notes = "购买VIP 测试支付用接口，无法在线上环境中使用")
    public ResponseEntity<Void> buy(@RequestBody VipBuyParam param) {
        VipPackage p = vipPackageService.getById(param.getPackageId());
        String userId = SecurityUtils.getUser().getUserId();
        Date now = new Date();
        /*if(userService.getById(userId).getIsVip() == 1){
            throw new YamiShopBindException("已经是VIP，无法购买VIP");
        }*/
        User user = userService.getById(userId);

//        如果是新人优惠套餐，且没有剩余次数，报错
        if(p.getMark()==0 && user.getDiscount()==0){
            throw new RuntimeException("已购买过新人优惠套餐，无法再次购买");
        }

        if (userService.getById(userId).getIsVip() == 0){
            user.setVipStartTime(now);
            user.setVipEndTime(DateUtil.offsetDay(now,p.getDayCount()));
        }else {//是VIP的话说明是续充
            Date endTime = userMapper.selectById(userId).getVipEndTime();
            user.setVipEndTime(DateUtil.offsetDay(endTime,p.getDayCount()));
        }
        user.setIsVip(1);
        user.setTodayUnlockSurplus(vipPackageService.getDailyFreeUnlockNum());
        if(userService.getById(userId).getIsFirstVip() == 0){
            user.setIsFirstVip(1);
            if (userService.getById(userId).getUppInvitatioCode() != null && !userService.getById(userId).getUppInvitatioCode().equals("")){
                //被邀请的朋友首次购买VIP，邀请人可以享受48小时内解密6个微信号时间和解密数量
                userMapper.uppCodeRepeatVip(userService.getById(userId).getUppInvitatioCode());
                if (userService.getById(userId).getSex().equals("M")){//当前用户是男生
                    if (userMapper.uppJudge(userService.getById(userId).getUppInvitatioCode()) != null){//上级用户性别不等于null
                        if (userMapper.uppJudge(userService.getById(userId).getUppInvitatioCode()).equals("F")){//如果上级是女生的话
                            //把rmb都反给女生
                            User user1 = userMapper.selectById(userId);//当前用户的信息
                            User user2 = userMapper.selectOne(new QueryWrapper<User>().eq("invitatio_code",user1.getUppInvitatioCode()));//上级用户信息
                            VipPackage vips = vipPackageMapper.selectOne(new QueryWrapper<VipPackage>().eq("id",param.getPackageId()));
                            user2.setWallet(user2.getWallet() + vips.getPrice());
                            userMapper.updateById(user2);
                        }
                    }
                }
            }
        }else if(userService.getById(userId).getIsFirstVip() == 1){
            if (now.before(userService.getById(userId).getVipEndTime())){
                //首次VIP续充
                user.setIsFirstVip(2);
            }
        }

        //如果是新人优惠套餐，则更新用户的优惠套餐数量
        if (p.getMark() == 0) {
            user.setDiscount(0);
            //设置解锁剩余次数为3
            user.setTodayUnlockSurplus(3);
            //设置是优惠vip标志
            user.setIsDiscountVip(1);
        }

        userService.updateById(user);
        return ResponseEntity.ok().build();
    }




}
